package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.page.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public void saveOrUpdate(Role role) {
        if(role.getId()!=null){
            //首先删除原来表中的关联关系
            roleMapper.deleteRelationWithPermission(role.getId());
            for (Permission permission : role.getPermissions()) {
                roleMapper.saveRelationWithPermission(role.getId(),permission.getId());
            }
            roleMapper.updateByPrimaryKey(role);
        }else {
            roleMapper.insert(role);
            for (Permission permission : role.getPermissions()) {
                roleMapper.saveRelationWithPermission(role.getId(),permission.getId());
            }
        }
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteRelationWithPermission(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int count = roleMapper.queryForCount(qo);
        PageResult pageResult = null;
        if(count == 0){
            pageResult = new PageResult(count, Collections.EMPTY_LIST);
        }
        List<Role> list = roleMapper.queryForList(qo);
        return new PageResult(count,list);
    }

    @Override
    public List<Permission> queryPermissionsByRoleId(Long roleId) {
        return permissionMapper.queryPermissionsByRoleId(roleId);
    }

}
